package com.jeesite.modules.app.examinate.extheory;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.modules.app.examinate.extheory.entity.AppExaminationBarbecue;
import com.jeesite.modules.app.examinate.extheory.service.AppExaminationBarbecueService;
import com.jeesite.modules.app.mockexam.theory.user.service.TmockexamTheoryUserService;
import com.jeesite.modules.app.util.time.DateUtils;
import com.jeesite.modules.conf.AppController;
import com.jeesite.modules.conf.MessageCode;
import com.jeesite.modules.conf.RedisUtils;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.EmployeePost;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.zx.barbecue.signup.entity.TbarbecueSignup;
import com.jeesite.modules.zx.barbecue.signup.service.TbarbecueSignupService;
import com.jeesite.modules.zx.examination.barbecue.post.entity.TexaminationBarbecuePost;
import com.jeesite.modules.zx.examination.barbecue.post.service.TexaminationBarbecuePostService;
import com.jeesite.modules.zx.examination.barbecue.user.entity.TexaminationBarbecueUser;
import com.jeesite.modules.zx.examination.barbecue.user.service.TexaminationBarbecueUserService;
import com.jeesite.modules.zx.examination.entity.Texamination;
import com.jeesite.modules.zx.examination.room.entity.TexaminationRoom;
import com.jeesite.modules.zx.examination.room.scene.entity.TexaminationRoomScene;
import com.jeesite.modules.zx.examination.room.scene.service.TexaminationRoomSceneService;
import com.jeesite.modules.zx.examination.room.service.TexaminationRoomService;
import com.jeesite.modules.zx.examination.service.TexaminationService;
import com.jeesite.modules.zx.examination.ticket.entity.TexaminationTicket;
import com.jeesite.modules.zx.examination.ticket.service.TexaminationTicketService;
import com.jeesite.modules.zx.examination.vip.entity.TexaminationVip;
import com.jeesite.modules.zx.examination.vip.service.TexaminationVipService;
import com.jeesite.modules.zx.user.vip.entity.TuserVip;
import com.jeesite.modules.zx.user.vip.service.TuserVipService;

@Controller
@RequestMapping(value = "/app/examinate/")
public class AppExaminationController {
    @Autowired
    private TexaminationService texaminationService;
    @Autowired
    private TexaminationVipService texaminationVipService;
    @Autowired
    private TuserVipService tuserVipService;
    @Autowired
    private TmockexamTheoryUserService tmockexamTheoryUserService;
    @Autowired
    private TbarbecueSignupService tbarbecueSignupService;
    @Autowired
    private TexaminationRoomService texaminationRoomService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private TexaminationTicketService texaminationTicketService;
    @Autowired
    private TexaminationRoomSceneService texaminationRoomSceneService;
    @Autowired
    private TexaminationBarbecuePostService texaminationBarbecuePostService;
    @Autowired
    private AppExaminationBarbecueService appExaminationBarbecueService;
    @Autowired
    private TexaminationBarbecueUserService texaminationBarbecueUserService;
    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping(value = "findList")
    public void findList(HttpServletRequest request, HttpServletResponse response) {
        String userId = request.getParameter("userId");
        if (StringUtils.isBlank(userId)) {
            AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
            return;
        }

        EmpUser empUser = empUserService.get(userId);
        if(empUser==null) {
        	AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户对象不存在");
            return;
        }
        String identity = empUser.getIdentity();
        if (!identity.equals("student")) {
            AppController.renderErrorString(response, MessageCode.ERROR_MESSAGE, "");
            return;
        }
        LocalDateTime now = LocalDateTime.now();
        //查询会员是否有效
        TuserVip userVip = new TuserVip();
        userVip.setUserId(userId);
        userVip.getSqlMap().getWhere().and("vip_starttime", QueryType.LT, now).and("vip_endtime", QueryType.GT, now);
        Long findCount = tuserVipService.findCount(userVip);
        //先查下考试内容
        Texamination texaminate = new Texamination();
        if (findCount != null && findCount > 0) {
            texaminate.setItem("理论考试");
        } else {
            texaminate.setItem("网络考试");
        }
        List<Texamination> findList = texaminationService.findList(texaminate);
        if (findList != null && findList.size() == 0) {
            if (findCount != null && findCount > 0) {
                AppController.renderErrorString(response, MessageCode.ERROR_MESSAGE, "没有查询到理论考试");
                return;
            } else {
                AppController.renderErrorString(response, MessageCode.ERROR_MESSAGE, "没有查询到网络考试");
                return;
            }
        }
        for (Texamination exam : findList) {
            Integer category = exam.getObjType();
            if (category != null) {
                String dictLabel = DictUtils.getDictLabel("t_examination_category", category.toString(), "");
                exam.setCategoryName(dictLabel);
            }
            TbarbecueSignup arg0 = new TbarbecueSignup();
            arg0.setCreateBy(userId);
            arg0.setBarbecueId(exam.getId());
            List<TbarbecueSignup> signUpList = tbarbecueSignupService.findList(arg0);
            if (signUpList != null && signUpList.size() > 0) {//已报名
                for (TbarbecueSignup ts : signUpList) {
                    Integer state = ts.getState();
                    if (state == 0) {
                        exam.setStateStr("已经报名正在审核");
                    } else if (state == 1) {
                        exam.setStateStr("报名通过审核");
                    } else if (state == 2) {
                        exam.setStateStr("报名数据驳回");
                    } else if (state == 3) {
                        exam.setStateStr("考试进行中");
                    } else if (state == 4) {
                        exam.setStateStr("已经完成考试");
                    }
                }
            } else {//未报名
                //判断用户
                exam = notSignUp(exam);
                if (exam == null) {
                    continue;
                }
            }
            TexaminationVip examVip = new TexaminationVip();
            examVip.setVipUser(userId);
            examVip.setExamId(exam.getId());
            List<TexaminationVip> examVipList = texaminationVipService.findList(examVip);
            exam.setExamVipList(examVipList);
        }
        JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(findList));
        AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
        return;

    }

    private Texamination notSignUp(Texamination barbecue) {
        LocalDateTime startDateTime = DateUtils.date2LocalDateTime(barbecue.getSignupStartTime());
        LocalDateTime endDateTime = DateUtils.date2LocalDateTime(barbecue.getSignupEndTime());
        LocalDateTime now = LocalDateTime.now();
        Long betweenDays = DateUtils.betweenDays(now, startDateTime);
        String  stateStr = "";
        if (betweenDays > 0) {
            stateStr = "距离报名开始时间:" + betweenDays + "天";
        } else {
            Long betweenHours = DateUtils.betweenHours(now, startDateTime);
            if (betweenHours > 0) {
                stateStr = "距离报名开始时间:" + betweenHours + "小时";
            } else {
                Long betweenDays2 = DateUtils.betweenDays(now, endDateTime);
                if (betweenDays2 > 0) {
                    stateStr = "距离报名结束时间:" + betweenDays2 + "天";
                } else{
                    Long betweenHours2 = DateUtils.betweenHours(now,endDateTime);
                    if (betweenHours2 > 0) {
                        stateStr = "距离报名结束时间:" + betweenHours2 + "小时";
                    } else if (betweenHours2 <= 0) {
                        stateStr = "报名已结束";
                    }
                }
            }
        }
        barbecue.setStateStr(stateStr);
        return barbecue;
    }

    @RequestMapping(value = "form")
    public void form(TexaminationTicket texaminationTicket, HttpServletRequest request, HttpServletResponse response) {
        List<TexaminationTicket> findList = texaminationTicketService.findList(texaminationTicket);
        JSONArray josn = JSONObject.parseArray(JsonMapper.toJson(findList));
        AppController.renderSuccessObject(response, josn, MessageCode.SUCCESS_ACK);
    }

    @RequestMapping(value = "signuped")
    public void signuped(Texamination entity, HttpServletRequest request, HttpServletResponse response) {
        String userId = request.getParameter("userId");
        if (StringUtils.isBlank(userId)) {
            AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
            return;
        }
        TbarbecueSignup arg0 = new TbarbecueSignup();
        arg0.setCreateBy(userId);
        List<Integer> states = new ArrayList<>();
        states.add(0);
        states.add(1);
        states.add(3);
        arg0.getSqlMap().getWhere().and("state", QueryType.IN, states);
        List<TbarbecueSignup> findList = tbarbecueSignupService.findList(arg0);
        List<String> list = new ArrayList<String>();
        Map<String, TbarbecueSignup> map = new HashMap<>();
        for (TbarbecueSignup ts : findList) {
            String barbecueId = ts.getBarbecueId();
            list.add(barbecueId);
            map.put(barbecueId, ts);
        }
        List<Texamination> findList2 = new ArrayList<>();
        if (list.size() > 0) {
            entity.getSqlMap().getWhere().and("id", QueryType.IN, list);
            findList2 = texaminationService.findList(entity);
            for (Texamination abb : findList2) {
                String id = abb.getId();
                TbarbecueSignup tbarbecueSignup = map.get(id);
                abb.setBarbecueSignup(tbarbecueSignup);
                Integer state = tbarbecueSignup.getState();
                if (state != null && state > 0) {
                    TexaminationVip examVip = new TexaminationVip();
                    examVip.setExamId(id);
                    examVip.setVipUser(userId);
                    List<TexaminationVip> findList3 = texaminationVipService.findList(examVip);
                    if (findList3 == null || findList3.size() == 0) {
                        abb.setStartTimeOf("还未分配考试");
                    } else {
                        TexaminationVip texaminationVip = findList3.get(0);
                        String scene = texaminationVip.getScene();
                        if (StringUtils.isNotBlank(scene)) {
                        	abb.setScene(scene);
                            TexaminationRoomScene texaminationRoomScene = texaminationRoomSceneService.get(scene);
                            Date barbecueStartDate = texaminationRoomScene.getStartDate();
                            if (barbecueStartDate != null) {
                                LocalDateTime starLocal = DateUtils.date2LocalDateTime(barbecueStartDate);
                                LocalDateTime now = LocalDateTime.now();
                                Long betweenMinutes = DateUtils.betweenMinutes(now, starLocal);
                                if (betweenMinutes > 0) {
                                    if (betweenMinutes > 60) {
                                        Long betweenHours = DateUtils.betweenHours(now, starLocal);
                                        if (betweenHours > 24) {
                                            Long betweenDays = DateUtils.betweenDays(now, starLocal);
                                            abb.setStartTimeOf("距离考试开始时间:" + betweenDays + "天");
                                        } else {
                                            abb.setStartTimeOf("距离考试开始时间:" + betweenHours + "小时");
                                        }
                                    } else {
                                        abb.setStartTimeOf("距离考试开始时间:" + betweenMinutes + "分钟");
                                    }
                                } else {
                                    Date barbecueEndDate = texaminationRoomScene.getEndDate();
                                    if (barbecueEndDate != null) {
                                        LocalDateTime endLocal = DateUtils.date2LocalDateTime(barbecueEndDate);
                                        Long betweenMinutesEnd = DateUtils.betweenMinutes(now, endLocal);
                                        if (betweenMinutesEnd > 0) {
                                            abb.setEndTimeOf("距离考试结束时间:" + betweenMinutesEnd + "分钟");
                                            abb.setOngoing("考试进行中");
                                            abb.setUpEndTime(betweenMinutesEnd);
                                        } else {
                                            abb.setEndTimeOf("考试结束");
                                        }
                                    }
                                }
                            }
                        } else {
                            abb.setStartTimeOf("还未指定考试场次");
                        }
                    }

                }
            }
        }
        JSONArray json = JSONObject.parseArray(JsonMapper.toJson(findList2));
        AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
    }
    @RequestMapping(value = "betweenMillis")
    public void betweenMillis(HttpServletRequest request,HttpServletResponse response) {
    	try {
			String scene=request.getParameter("scene");
			boolean hasKey = redisUtils.hasKey(scene);
			if(hasKey) {
				Object object = redisUtils.get(scene);
				long betweenTime=betweenTime((Date)object);
				AppController.renderSuccessObject(response, betweenTime, MessageCode.SUCCESS_ACK);
			}else {
				AppController.renderSuccessObject(response, 0, MessageCode.SUCCESS_ACK);
			}
		} catch (Exception e) {
			e.printStackTrace();
			AppController.renderErrorString(response, MessageCode.ERROR_MESSAGE, "系统异常");
		}
    }
    private long betweenTime(Date betweenTime) {
    	LocalDateTime starLocal = DateUtils.date2LocalDateTime(betweenTime);
        LocalDateTime now = LocalDateTime.now();
        Long betweenMillis = DateUtils.betweenMillis(now, starLocal);
        return betweenMillis;
    }
    /**
     * 针对不同的岗位进行查询
     *
     * @param entity
     * @param request
     * @param response
     */
    @RequestMapping(value = "headList")
    public void headList(AppExaminationBarbecue entity, HttpServletRequest request, HttpServletResponse response) {
        String examId = entity.getExamId();
        if (StringUtils.isBlank(examId)) {
            AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "查询标识");
            return;
        }
        String userId = request.getParameter("userId");
        if (StringUtils.isBlank(userId)) {
            AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
            return;
        }
        //查询用户的岗位
        EmpUser empUser = empUserService.get(userId);
        List<String> postList = new ArrayList<>();
        if (empUser != null) {
            Employee employee = empUser.getEmployee();
            List<EmployeePost> findEmployeePostList = employeeService.findEmployeePostList(employee);
            for (EmployeePost post : findEmployeePostList) {
                String postCode = post.getPostCode();
                postList.add(postCode);
            }
        }
        //查询理论考试对应的考题
        entity.setParentCode("0");
        List<AppExaminationBarbecue> findList = appExaminationBarbecueService.findList(entity);
        List<AppExaminationBarbecue> barbeList = new ArrayList<>();
        //遍历考题，找出对应岗位的考题
        for (AppExaminationBarbecue aeb : findList) {
            String id = aeb.getId();
            //如果用户设置了岗位
            if (postList.size() > 0) {
                TexaminationBarbecuePost texamination = new TexaminationBarbecuePost();
                texamination.setParentId(examId);
                texamination.setBarbecueId(id);
                texamination.getSqlMap().getWhere().and("post", QueryType.IN, postList);
                List<TexaminationBarbecuePost> barPostList = texaminationBarbecuePostService.findList(texamination);
                if (barPostList != null && barPostList.size() > 0) {//在考试范围内
                    barbeList.add(aeb);
                    break;
                }
            } else {
                //如果没有设置岗位，查找考题中没有设置岗位的考题给客户
                String post = aeb.getPost();
                if (StringUtils.isBlank(post)) {
                    barbeList.add(aeb);
                    break;
                }
            }
        }
        if (barbeList != null && barbeList.size() > 0) {
            JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(barbeList));
            AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
        } else {
            //没有考题时直接把第一条数据给客户答题
            barbeList.add(findList.get(0));
            JSONArray parseArray = JSONObject.parseArray(JsonMapper.toJson(barbeList));
            AppController.renderSuccessObject(response, parseArray, MessageCode.SUCCESS_ACK);
        }
    }

    /**
     * 理论记录
     */
    @RequestMapping(value = "examinateRecord")
    public void examinateRecord(AppExaminationBarbecue entity, HttpServletRequest request, HttpServletResponse response) {
        String userId = request.getParameter("userId");
        if (StringUtils.isBlank(userId)) {
            AppController.renderErrorString(response, MessageCode.PARAMETER_IS_NEED, "用户标识");
            return;
        }
        TexaminationBarbecueUser barbecuseUser = new TexaminationBarbecueUser();
        barbecuseUser.setUserId(userId);
        barbecuseUser.getSqlMap().getWhere().and("type", QueryType.GT, "1");
        List<TexaminationBarbecueUser> findPage2 = texaminationBarbecueUserService.findList(barbecuseUser);
        for (TexaminationBarbecueUser barUser : findPage2) {
            String theoryId = barUser.getTheoryId();
            if (StringUtils.isNotBlank(theoryId)) {
                Texamination texamination = texaminationService.get(theoryId);
                String objName = texamination.getObjName();
                barUser.setTheoryName(objName);
            }
            String postId = barUser.getPostId();
            if (StringUtils.isNotBlank(postId)) {
                AppExaminationBarbecue appExaminationBarbecue = appExaminationBarbecueService.get(postId);
                String objName = appExaminationBarbecue.getObjName();
                barUser.setPostName(objName);
            }
        }
        JSONArray json = JSONObject.parseArray(JsonMapper.toJson(findPage2));
        AppController.renderSuccessObject(response, json, MessageCode.SUCCESS_ACK);
    }
}
